import 'package:flutter/material.dart';
import 'package:location/location.dart';

class LocationSharingWidget extends StatefulWidget {
  const LocationSharingWidget({Key? key}) : super(key: key);

  @override
  _LocationSharingWidgetState createState() => _LocationSharingWidgetState();
}

class _LocationSharingWidgetState extends State<LocationSharingWidget> {
  final Location _location = Location();
  bool _isLocationShared = false;
  LocationData? _locationData;

  @override
  void initState() {
    super.initState();
    _checkLocationPermission();
  }

  Future<void> _checkLocationPermission() async {
    bool serviceEnabled = await _location.serviceEnabled();
    if (!serviceEnabled) {
      serviceEnabled = await _location.requestService();
      if (!serviceEnabled) {
        return;
      }
    }

    PermissionStatus permissionGranted = await _location.hasPermission();
    if (permissionGranted == PermissionStatus.denied) {
      permissionGranted = await _location.requestPermission();
      if (permissionGranted != PermissionStatus.granted) {
        return;
      }
    }
  }

  Future<void> _toggleLocationSharing() async {
    if (_isLocationShared) {
      setState(() {
        _isLocationShared = false;
        _locationData = null;
      });
    } else {
      await _checkLocationPermission();

      try {
        final locationData = await _location.getLocation();
        setState(() {
          _isLocationShared = true;
          _locationData = locationData;
        });
      } catch (e) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('获取位置失败: $e')),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '位置共享',
                  style: Theme.of(context).textTheme.headline6,
                ),
                Switch(
                  value: _isLocationShared,
                  onChanged: (value) => _toggleLocationSharing(),
                  activeColor: Colors.pink,
                ),
              ],
            ),
            if (_isLocationShared && _locationData != null) ...[
              const SizedBox(height: 8),
              Text('纬度: ${_locationData!.latitude?.toStringAsFixed(6)}'),
              Text('经度: ${_locationData!.longitude?.toStringAsFixed(6)}'),
              const SizedBox(height: 8),
              Container(
                height: 150,
                width: double.infinity,
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(8.0),
                ),
                child: const Center(
                  child: Text('地图将在这里显示'),
                ),
              ),
            ] else ...[
              const SizedBox(height: 8),
              const Text('开启位置共享，让对方知道你在哪里'),
            ],
          ],
        ),
      ),
    );
  }
}

